//
//  UserRegisterController.swift
//  chat
//
//  Created by 崔世强 on 2018/10/26.
//  Copyright © 2018 崔世强. All rights reserved.
//

import UIKit
import Toast_Swift

class UserRegisterController: UIViewController {
    
    @IBOutlet weak var cancelBtn: UIButton!
    
    @IBOutlet weak var phoneField: UITextField!
    
    @IBOutlet weak var validateBtn: UIButton!
    
    @IBOutlet weak var pwdField: UITextField!
    
    @IBOutlet weak var registerBtn: UIButton!
    
    @IBOutlet weak var validateCodeField: UITextField!
    
    @IBOutlet weak var phoneViewTopConstraint: NSLayoutConstraint!
    
    @IBAction func cancelBtnClick(_ sender: Any) {
        self.dismiss(animated: true, completion: nil)
    }
    
    lazy var service = UserService()
    
    @IBAction func registerBtnClick(_ sender: UIButton) {
        let userName = self.phoneField.text!
        let pwd = self.pwdField.text!
        let validateCode = self.validateCodeField.text!
        
        if !pwdValid(pwd:pwd,confirm:validateCode) {
            self.view.makeToast("两次密码输入不一致",position:.center)
            return
        }
         self.view.makeModalToastActivity(.center)
        service.register(userName: userName, pwd: pwd, validateCode: validateCode) {[unowned self] (success, msg, userId) in
            DispatchQueue.main.async {
                self.view.hideModalToastActivity()
                if success {
                    self.service.login(userId!,"\(userName)")
                    self.dismiss(animated: true, completion: {
                        let tabBar = ChatTabBarController()
                        UIApplication.shared.keyWindow?.rootViewController = tabBar
                    })
                } else {
                    self.view.makeToast("\(msg!)", position:.center)
                }
            }
        }
    }
    func pwdValid(pwd:String,confirm:String) -> Bool {
        return pwd == confirm
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        cancelBtn.setTitleColor(kBtnGreen, for: .normal)
        
        validateBtn.isEnabled = false
        validateBtn.setTitleColor(kBtnGreen, for: .normal)
        validateBtn.setTitleColor(kBtnDisabledGreen, for: .disabled)
        validateBtn.addTarget(self, action: #selector(validateBtnClicked(_:)), for: .touchUpInside)
        
        registerBtn.backgroundColor = kBtnGreen
        registerBtn.setBackgroundImage((kBtnGreen).trans2Image(), for: .normal)
        registerBtn.setBackgroundImage((kBtnDisabledGreen).trans2Image(), for: .disabled)
        registerBtn.layer.cornerRadius = 5.0
        registerBtn.layer.masksToBounds = true
        
        phoneField.addTarget(self, action: #selector(valueDidChange(_:)), for: .editingChanged)
        validateCodeField.addTarget(self, action: #selector(valueDidChange(_:)), for: .editingChanged)
        pwdField.addTarget(self, action: #selector(valueDidChange(_:)), for: .editingChanged)
        
    }
    
}

extension UserRegisterController {
    @objc func validateBtnClicked(_ btn:UIButton) {
        validateBtn.isEnabled = false
        let time = 60
        btn.setTitle("\(time)S", for: .disabled)
        btn.startCountDown(time: TimeInterval(time), tick: 1, onTick: { [weak btn] (timer, times, remain) in
            btn?.setTitle("\(Int(remain))S", for: .disabled)
        }) { [weak btn] (times) in
            btn?.isEnabled = true
        }
    }
    
    
    @objc func valueDidChange(_ textField: UITextField) {
        checkRegBtnCanUse()
        if textField == self.phoneField {
            checkValidBtnCanUse()
        }
    }
    
    func checkRegBtnCanUse() {
        let phoneFieldEmpty = self.phoneField.text?.isEmpty ?? true
        let pwdFieldEmpty = self.pwdField.text?.isEmpty ?? true
        let validateCodeFieldEmpty = self.validateCodeField.text?.isEmpty ?? true
        self.registerBtn.isEnabled = !phoneFieldEmpty && !pwdFieldEmpty && !validateCodeFieldEmpty
    }
    
    func checkValidBtnCanUse() {
        self.validateBtn.isEnabled = self.phoneField.text?.isPhoneNumber() ?? false
    }
}
